<template>
  <div class="b-code relative flex justify-around">
    <input ref="bcode"
           id="bcode"
           type="tel"
           v-model="code"
           @focus="focused = true"
           @blur="focused = false"
           maxlength="6" />
    <label for="bcode"
           class="react"
           v-for="(item,index) in bits"
           :class="{'animated': focused && active === index}"
           :key="index">
      {{codeArr[index]}}
    </label>
  </div>
</template>

<script>
export default {
  name: 'BCode',
  props: {
    bits: {
      type: Number,
      default: 6
    },
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      focused: true
    }
  },
  computed: {
    codeArr () {
      return this.code.split('')
    },
    active () {
      return this.codeArr.length
    },
    code: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },
  mounted(){
    this.$refs.bcode.focus()
  },
  watch: {
    code (val) {
      this.code = val.replace(/[^\d]/g, '')
    }
  },
  methods: {

  }
}
</script>
<style lang="scss" scoped>
.b-code {
  input {
    position: absolute;
    top: -100%;
    left: -666666px;
    opacity: 0;
  }
  .react {
    position: relative;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    display: inline-block;
    background: #ffffff;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #dde1e6;
    &.animated::before {
      display: block;
      position: absolute;
      left: 50%;
      top: 20%;
      width: 1px;
      height: 60%;
      content: "";
      background-color: #333333;
      animation-name: coruscate;
      animation-duration: 1s;
      animation-iteration-count: infinite;
      animation-fill-mode: both;
    }
  }
}

@keyframes coruscate {
  0% {
    opacity: 0;
  }
  25% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  75% {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
</style>